package com.dnjn.happiness.biz.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dnjn.happiness.biz.domain.Communicate;
import com.dnjn.happiness.biz.domain.CommunicateVO;
import com.dnjn.happiness.biz.domain.vo.CommunicateBean;
import com.dnjn.happiness.biz.service.ICommunicateService;
import com.dnjn.happiness.common.core.constant.Constants;
import com.dnjn.happiness.common.core.model.CommunicateModel;
import com.dnjn.happiness.common.security.utils.VerifyUtil;
import com.dnjn.happiness.common.core.constant.SecurityConstants;
import com.dnjn.happiness.common.core.domain.R;
import com.dnjn.happiness.common.core.utils.StringUtils;
import com.dnjn.happiness.common.cloud.controller.BaseController;
import com.dnjn.happiness.common.core.web.domain.AjaxResult;
import com.dnjn.happiness.common.log.annotation.Log;
import com.dnjn.happiness.common.log.enums.BusinessType;
import com.dnjn.happiness.common.security.annotation.InnerAuth;
import com.dnjn.happiness.common.security.annotation.RequiresPermissions;
import com.dnjn.happiness.common.security.utils.SecurityUtils;
import com.dnjn.happiness.system.api.RemoteDeptService;
import com.dnjn.happiness.system.api.RemoteTeamService;
import com.dnjn.happiness.system.api.RemoteUserService;
import com.dnjn.happiness.system.api.domain.SysDept;
import com.dnjn.happiness.system.api.domain.SysTeam;
import com.dnjn.happiness.system.api.domain.SysUser;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

;

/**
 * 沟通Controller
 *
 * @author happiness
 * @date 2023-10-28
 */
@Tag(name = "admin biz communicate 后台沟通", description = "沟通")
@RestController
@RequestMapping("/admin/communicate") // 里边看后缀 Admin 是那天晚上拷贝一份的时候加的
public class AdminCommunicateController extends BaseController {
    @Autowired
    private ICommunicateService communicateService;

    @Autowired
    private RemoteUserService userService;

    @Autowired
    private RemoteDeptService deptService;

    @Autowired
    private RemoteTeamService teamService;

    @InnerAuth
    @GetMapping("/updateHappyWhenCommunicating/{userId}/{scoreTime}/{happinessScores}")
    public void updateHappyWhenCommunicating(@PathVariable Long userId,@PathVariable String scoreTime,@PathVariable Integer happinessScores) {

        communicateService.updateCommunicateWhenCommunicating(userId,scoreTime,happinessScores);


    }

    @InnerAuth
    @GetMapping("/getCommunicateListByStatus/{status}")
    public R<List<Communicate>> getCommunicateListByStatus(@PathVariable String status) {
        return R.ok(communicateService.lambdaQuery().eq(Communicate::getDeleted, Constants.UNDELETED).eq(Communicate::getCommunicateStatus, status).list());
    }

    @InnerAuth
    @GetMapping("/handleScoreEvent/{userId}/{score}")
    public R<Boolean> handleScoreEvent(@PathVariable Long userId,@PathVariable Integer score) {
        return R.ok(communicateService.handleScoreEvent(userId,score));
    }

    @InnerAuth
    @GetMapping("/updateCommunicateDeleted/{communicateId}")
    public void updateCommunicateDeleted(@PathVariable Long communicateId) {
        communicateService.lambdaUpdate().set(Communicate::getCommunicateResultAddDeleted, '1').eq(Communicate::getCommunicateId, communicateId).update();
    }

    @InnerAuth
    @GetMapping("/updateByCommunicateId/{modeladdResultsScore}/{defultsScore}/{format}/{communicateId}")
    public void updateByCommunicateId(@PathVariable Double modeladdResultsScore, @PathVariable Double defultsScore,@PathVariable String format,@PathVariable Long communicateId) {
        communicateService.lambdaUpdate()
                .set(Communicate::getCommunicateResultAddScore, modeladdResultsScore)
                .set(Communicate::getCommunicateDefult, defultsScore)
                .set(Communicate::getScoreTime, format)
                .set(Communicate::getCommunicateResultAddDeleted, '0').eq(Communicate::getCommunicateId,communicateId).update();

    }

    @InnerAuth
    @GetMapping("/deleteByStatus/{value}")
    public void deleteByStatus(@PathVariable String value) {
        communicateService.deleteByStatus(value);
    }

    @InnerAuth
    @GetMapping("/getInfoById/{communicateId}")
    public R<Communicate> getInfoById(@PathVariable Long communicateId) {
        Communicate one = communicateService.lambdaQuery().eq(Communicate::getCommunicateId, communicateId)
                .eq(Communicate::getCommunicateResultAddDeleted, '0').one();
        return R.ok(one);
    }

    @InnerAuth
    @PutMapping("/delCommunicate/{communicateId}")
    public R<Boolean> delCommunicate(@PathVariable Long communicateId) {
        return R.ok(communicateService.lambdaUpdate().set(Communicate::getCommunicateResultAddDeleted, '1').eq(Communicate::getCommunicateId, communicateId).update());
    }

    @InnerAuth
    @GetMapping("/getResult")
    public R<Communicate> getResult(@RequestParam Long userId,@RequestParam String lastTime,@RequestParam String scoreTime) {
        return R.ok(communicateService.getResult(userId,lastTime,scoreTime));
    }


    @InnerAuth
    @GetMapping("/updateComSurvyId/{surveyId}/{communicateId}")
    public void updateComSurvyId(@PathVariable Long surveyId, @PathVariable Long communicateId) {
        communicateService.updateComSurvyId(surveyId, communicateId);
    }

    /**
     * 后台首页-需沟通
     */
    @PostMapping("/getCommunicatePage")
    @RequiresPermissions("biz:communicate:query")
    @Operation(summary = "后台首页-需沟通")
    public AjaxResult getCommunicatePage(@RequestBody Communicate communicate, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        Page page = Page.of(current, size);
//        communicate.setCommunicateStatus("0");
        communicate.setType("queryCommunicate");
        if (VerifyUtil.whetherAllPermissions()) {
            communicate.setWhetherAllPermissions(true);
        } else {
            communicate.setWhetherAllPermissions(false);
        }
        communicate.setDeptId(SecurityUtils.getLoginUser().getDeptId());
        Page<Communicate> list = communicateService.getCommunicatePage(page, communicate);
        return success(list);
    }

    /**
     * 后台首页-当日已指派
     */
    @PostMapping("/getTodayAssignPage")
    @RequiresPermissions("biz:communicate:query")
    @Operation(summary = "后台首页-当日已指派")
    public AjaxResult getTodayAssignPage(@RequestBody Communicate communicate, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        Page page = Page.of(current, size);
//        communicate.setCommunicateStatus("1");
        communicate.setType("queryTodayAssign");
        if (VerifyUtil.whetherAllPermissions()) {
            communicate.setWhetherAllPermissions(true);
        } else {
            communicate.setWhetherAllPermissions(false);
        }
        communicate.setDeptId(SecurityUtils.getLoginUser().getDeptId());
        Page<Communicate> list = communicateService.getCommunicatePage(page, communicate);
        return success(list);
    }

    /**
     * 后台首页去指派
     */
    @RequiresPermissions("biz:communicate:edit")
    @Operation(summary = "后台首页去指派", description = "必传: fromUserId:沟通发起人; userId:沟通人 operUserId:实际沟通人;communicateType是INTERVIEW")
    @PostMapping("/toAssignCommunicate")
    public AjaxResult toAssignCommunicate(@RequestBody Communicate communicate) {
        Long userId = SecurityUtils.getUserId();
        communicate.setFromUserId(userId);
        Assert.notNull(communicate.getFromUserId(), "沟通发起人不能为空");
        Assert.notNull(communicate.getUserId(), "沟通人不能为空");
        Assert.notNull(communicate.getOperUserId(), "实际沟通人不能为空");
        return toAjax(communicateService.toAssignCommunicate(communicate));
    }

    /**
     * 后台首页填写沟通结果
     */
    @RequiresPermissions("biz:communicate:edit")
    @Operation(summary = "后台首页填写沟通结果", description = "必传: fromUserId:沟通发起人; userId:沟通人 operUserId:实际沟通人;communicateType是INTERVIEW")
    @PostMapping("/editResultCommunicate")
    public AjaxResult editResultCommunicate(@RequestBody Communicate communicate) {

        communicate.setFromUserId(SecurityUtils.getUserId());
        Assert.notNull(communicate.getUserId(), "沟通人不能为空");

        communicateService.updateResultCommunicate(communicate);

        return success();
    }


    /**
     * 修改沟通
     */
    @RequiresPermissions("biz:communicate:edit")
    @Log(title = "沟通", businessType = BusinessType.UPDATE)
    @Operation(summary = "更新沟通", description = "① 结束沟通:传参: communicateStatus:1; ② 填写沟通结果 必传:communicateId(沟通id);result(沟通结果);etypeId(情绪id);communicateStatus(沟通状态改为1)")
    @PutMapping("/updateAdmin")
    public AjaxResult editAdmin(@RequestBody Communicate communicate) {
        Assert.notNull(communicate.getUserId(), "被沟通人不能为空");

        return toAjax(communicateService.updateById(communicate));
    }


    @RequiresPermissions("biz:communicate:add")
    @Log(title = "沟通", businessType = BusinessType.INSERT)
    @Operation(summary = "添加沟通", description = "必传: fromUserId:沟通发起人; userId:沟通人 operUserId:实际沟通人;communicateType是INTERVIEW")
    @PostMapping("/addCommunicate")
    public AjaxResult addCommunicate(@RequestBody Communicate communicate) {
        Long userId = SecurityUtils.getUserId();
        communicate.setFromUserId(userId);
        Assert.notNull(communicate.getFromUserId(), "沟通发起人不能为空");
        Assert.notNull(communicate.getUserId(), "沟通人不能为空");
        Assert.notNull(communicate.getOperUserId(), "实际沟通人不能为空");

        communicate.setCreateBy(SecurityUtils.getUsername());
        communicate.setCommunicateStatus("0");
        communicate.setCommunicateType("INTERVIEW");
        return toAjax(communicateService.saveCommunicate(communicate));
    }


    @RequiresPermissions("biz:communicate:query")
    @Log(title = "沟通", businessType = BusinessType.INSERT)
    @Operation(summary = "查询user_id有没有被指派", description = "必传: userId,查询userId有没有被指派,前端根据返回数据判断显示已指派还是去指派")
    @PostMapping("/queryUserId")
    public AjaxResult queryUserId(@Parameter(required = true) Long userId) {

        QueryWrapper<Communicate> wrapper = new QueryWrapper<>();
        //0 已经指派
        wrapper.eq("user_id", userId).eq("communicate_status", "0");
        Communicate one = communicateService.getOne(wrapper);
        return AjaxResult.success(one);
    }

    //档案管理-访谈记录
    //
    //访谈人是领导  ; 沟通人是下级
    //
    //访谈记录是所有  后台
    @RequiresPermissions("biz:communicate:query")
    @PostMapping("/queryCommunicate")
    @Operation(summary = "queryComByUserId沟通记录", description = "① 个人详情-访谈记录 必传: userId 可以选择沟通人 operUserId ; ② 我的-沟通历史 必传: operUserId 可选:gouTongNickname")
    public AjaxResult queryComByUserId(@RequestBody Communicate domain, @Parameter(required = true) boolean SurveyOrInteview, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        if (SurveyOrInteview) {
            domain.setCommunicateType("SURVEY");//问卷记录
        } else {
            domain.setCommunicateType("INTERVIEW");//访谈
        }
        if (VerifyUtil.whetherAllPermissions()) {
            domain.setWhetherAllPermissions(true);
        } else {
            domain.setWhetherAllPermissions(false);
        }
        Page<Communicate> list = communicateService.queryComByUserId(domain, Page.of(current, size).addOrder(OrderItem.desc("communicate_id")));

        return success(list);

    }


    @RequiresPermissions("biz:communicate:query")
    @PostMapping("/queryCommunicateTeamAdmin")
    @Operation(summary = "queryCommunicateTeamAdmin后台首页指派给我的", description = "传operUserId")
    public AjaxResult queryCommunicateTeamAdmin(@RequestBody Communicate domain, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
//        if (SurveyOrInteview) {
//            domain.setCommunicateType("SURVEY");//问卷记录
//        } else {
//            domain.setCommunicateType("INTERVIEW");//访谈
//        }

        Page<CommunicateVO> list = communicateService.queryCommunicateTeam(domain, Page.of(current, size).addOrder(OrderItem.desc("hlbean")));

        communicateService.getCountByUserId(list.getRecords());


        return success(list);

    }


//后台---

    /**
     * 查询沟通列表
     */
    @RequiresPermissions("biz:communicate:list")
    @PostMapping("/list")
    public AjaxResult list(@RequestBody Communicate vo, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        if (VerifyUtil.whetherAllPermissions()) {
            vo.setWhetherAllPermissions(true);
        } else {
            vo.setWhetherAllPermissions(false);
        }
        Page<Communicate> list = communicateService.queryComByUserId(vo, Page.of(current, size).addOrder(OrderItem.desc("score_time")));
        if (!CollectionUtils.isEmpty(list.getRecords())) {
            for (Communicate communicate : list.getRecords()) {
                String operDeptId = communicate.getOperDeptId();
                if (!StringUtils.isEmpty(operDeptId)) {
                    R<SysDept> result = deptService.getInfoById(Long.parseLong(operDeptId), SecurityConstants.INNER);
                    if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
                        communicate.setOperDeptName(result.getData().getDeptName());
                    }
                }
                String userDeptId = communicate.getUserDeptId();
                if (!StringUtils.isEmpty(userDeptId)) {
                    R<SysDept> result = deptService.getInfoById(Long.parseLong(operDeptId), SecurityConstants.INNER);
                    if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
                        communicate.setUserDeptName(result.getData().getDeptName());
                    }
                }
            }
        }
        return success(list);
    }


    /**
     * 获取沟通详细信息
     */
    @RequiresPermissions("biz:communicate:query")
    @GetMapping(value = "/{communicateId}")
    public AjaxResult get(@PathVariable("communicateId") Long communicateId) {
        return success(communicateService.getCommunicateIdById(communicateId));
    }

    /**
     * 新增沟通
     */
    //@Log(title = "沟通", businessType = BusinessType.INSERT)
    @RequiresPermissions("biz:communicate:add")
    @PostMapping()
    public AjaxResult add(@RequestBody Communicate vo) {
        Communicate communicate = new Communicate();
        communicate.setCreateBy(SecurityUtils.getUsername());
        return toAjax(communicateService.save(communicate));
    }

    /**
     * 修改沟通
     */
    //@Log(title = "沟通", businessType = BusinessType.UPDATE)
    @Deprecated
    @RequiresPermissions("biz:communicate:edit")
    @PutMapping()
    public AjaxResult edit1(@RequestBody Communicate vo) {
        Communicate communicate = new Communicate();
        return toAjax(communicateService.updateById(communicate));
    }


    @RequiresPermissions("biz:communicate:remove")
    @DeleteMapping("/{communicate_ids}")
    public AjaxResult remove(@PathVariable Long communicate_ids) {
        return toAjax(communicateService.lambdaUpdate().eq(Communicate::getCommunicateId, communicate_ids).set(Communicate::getDeleted, "1").update());
    }

    @GetMapping("/queryUserListByUserId/{userId}")
    @RequiresPermissions("@ss.hasPermi('biz:communicate:query')")
    public AjaxResult queryUserListByUserId(@PathVariable Long userId) {
        SysDept currentDept = null;
        R<SysDept> currentDeptResult = deptService.selectSuperDeptList(SecurityUtils.getUserId(), SecurityConstants.INNER);
        if (StringUtils.isNotNull(currentDeptResult) && StringUtils.isNotNull(currentDeptResult)){
            currentDept = currentDeptResult.getData();
        }
        SysDept dept = null;
        R<SysDept> deptResult = deptService.selectSuperDeptList(userId, SecurityConstants.INNER);
        if (StringUtils.isNotNull(deptResult) && StringUtils.isNotNull(deptResult)){
            dept = deptResult.getData();
        }
        List<SysUser> userList = new ArrayList<>();
        Set<Long> userIds = new HashSet<>();
        if (null != currentDept && null != dept) {
            List<String> currentAncestors = Arrays.stream(currentDept.getAncestors().split(",")).collect(Collectors.toList());
            currentAncestors.add(currentDept.getDeptId().toString());
            List<String> ancestors = Arrays.stream(dept.getAncestors().split(",")).collect(Collectors.toList());
            ancestors.add(dept.getDeptId().toString());
            for (String deptId : ancestors) {
                if (!currentAncestors.contains(deptId)) {
                    SysDept sysDept = null;
                    R<SysDept> result = deptService.getInfoById(Long.parseLong(deptId), SecurityConstants.INNER);
                    if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result)){
                        sysDept = result.getData();
                    }
                    if (!ObjectUtils.isEmpty(sysDept.getLeaderId()) && !userId.equals(sysDept.getLeaderId())) {
                        userIds.add(sysDept.getLeaderId());
//
                    }
                }
            }
            if (userIds.size() > 0) {
                for (Long id : userIds) {
                    SysUser sysUser = null;
                    R<SysUser> result = userService.selectUserInfo(id, SecurityConstants.INNER);
                    if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result)){
                        sysUser = result.getData();
                    }
                    if (null != sysUser) {

                        userList.add(sysUser);
                    }
                }
            }


            return AjaxResult.success(userList);
        }

        return AjaxResult.success(userList);

    }



    /**
     * 统计当日新增沟通数量
     */
    @GetMapping("/todayCommunicateTotal")
    @RequiresPermissions("biz:communicate:query")
    public AjaxResult todayCommunicateTotal(@RequestParam(required = false) Long deptId) {
        Communicate domain = new Communicate();
        domain.setCurrDate(LocalDate.now());
        domain.setCommunicateStatus("3");
        if (Objects.isNull(deptId)) {
            deptId = SecurityUtils.getLoginUser().getDeptId();
        }
        domain.setDeptId(deptId);
        if (VerifyUtil.whetherAllPermissions()) {
            domain.setWhetherAllPermissions(true);
        } else {
            domain.setWhetherAllPermissions(false);
        }
        Page<Communicate> list = communicateService.queryComByUserId(domain, Page.of(1, 10).addOrder(OrderItem.desc("communicate_id")));
        return AjaxResult.success(list.getTotal());
    }


    /**
     * 后台首页-需沟通 - 改
     */
    @PostMapping("/getCommunicateListPage")
    @RequiresPermissions("biz:communicate:query")
    @Operation(summary = "后台首页-需沟通- 改")
    public AjaxResult getCommunicateListPage(@RequestBody Communicate communicate, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        Page page = Page.of(current, size);
//        communicate.setCommunicateStatus("0");
        communicate.setType("queryCommunicate");

        Long userId = SecurityUtils.getUserId();
        communicate.setUserId(userId);
        SysTeam team = null;
        R<SysTeam> result = teamService.getInfoById(userId, SecurityConstants.INNER);
        if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
            team = result.getData();
        }
        if (VerifyUtil.whetherAllPermissions()) {
            communicate.setWhetherAllPermissions(true);
        } else {
            if (null == team) {
                return success(new Page<Communicate>());
            } else {
                communicate.setTeamId(team.getTeamId());
            }
            communicate.setWhetherAllPermissions(false);
        }
        /*Long userId = SecurityUtils.getUserId();
        List<SysTeam> sysTeamList = teamService.lambdaQuery().and((Wrappers)->Wrappers.eq(SysTeam::getParentId,userId).or().eq(SysTeam::getSuperId,userId)).list();
        List<Long> longList = sysTeamList.stream().map(SysTeam::getUserId).collect(Collectors.toList());
        Map<String,Object> map = new HashMap<>();
        map.put("userIds",longList);
        if (whetherAllPermissions()){
            map.put("whetherAllPermissions",true);
        }else {
            map.put("whetherAllPermissions",false);
        }*/


        Page<Communicate> list = communicateService.getPage(page, communicate);
        return success(list);
    }
    /**
     * 首页 查询去指派 -》 执行列表 -改
     * 查询 当前登录用户Id，被沟通人用户id
     * 查看被指派人得上级，和 上上级不是自己的
     *
     * @param :currentUserId 当前登录用户id
     * @param :userId        被沟通人id
     */
    @GetMapping("/newQueryUserListByUserId/{userId}")
    @RequiresPermissions("biz:communicate:query")
    public AjaxResult newQueryUserListByUserId(@PathVariable Long userId) {
        Assert.notNull(userId, "被指派人用户id不能为空");
        List<SysTeam> list = new ArrayList<>();
        //指派人Id
        Long currentUserId = SecurityUtils.getUserId();
        SysTeam currTeam = null;
        R<SysTeam> result = teamService.getInfoById(userId, SecurityConstants.INNER);
        if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
            currTeam = result.getData();
        }
        if (null == currTeam) {
            return AjaxResult.success(list);
        }
        //当前登陆人的team，
        SysTeam sysTeam = null;
        R<SysTeam> resultCur = teamService.getInfoById(currentUserId, SecurityConstants.INNER);
        if (StringUtils.isNotNull(resultCur) && StringUtils.isNotNull(resultCur.getData())) {
            sysTeam = resultCur.getData();
        }

        if (!ObjectUtils.isEmpty(currTeam.getParentId())) {
            SysTeam parentTeam = null;
            R<SysTeam> resultParentTeam = teamService.queryInfoByTeamId(currTeam.getParentId(), SecurityConstants.INNER);
            if (StringUtils.isNotNull(resultParentTeam) && StringUtils.isNotNull(resultParentTeam.getData())) {
                parentTeam = resultParentTeam.getData();
            }
            if (null != parentTeam) {
                //如果是超级管理员，返回直接上级
                if (VerifyUtil.whetherAllPermissions()) {
                    list.add(parentTeam);
                    return AjaxResult.success(list);
                } else {
                    if (!parentTeam.getUserId().equals(currentUserId) && sysTeam.getLevel() <= parentTeam.getLevel()) {
                        list.add(parentTeam);
                    }
                }
            }
        }
        if (!ObjectUtils.isEmpty(currTeam.getSuperId()) && !VerifyUtil.whetherAllPermissions()) {
            SysTeam superTeam = null;
            R<SysTeam> resultSuperTeam = teamService.queryInfoByTeamId(currTeam.getSuperId(), SecurityConstants.INNER);
            if (StringUtils.isNotNull(resultSuperTeam) && StringUtils.isNotNull(resultSuperTeam.getData())) {
                superTeam = resultSuperTeam.getData();
            }
            if (!superTeam.getUserId().equals(currentUserId)) {
                //不能指派给当前登录人的上级
                if (!ObjectUtils.isEmpty(sysTeam.getParentId()) && !sysTeam.getParentId().equals(superTeam.getTeamId()) && sysTeam.getLevel() <= superTeam.getLevel()) {
                    list.add(superTeam);
                }
            }
        }
        return AjaxResult.success(list);
    }

    /**
     * 建议查询 查询去指派 -》 执行列表 -改
     * 如果是超级管理员登录那么指派的时候显示该人的所有上级。
     * 普通管理员查看被指派人得上级，和 上上级不是自己的
     * 查询 当前登录用户Id，被沟通人用户id
     *
     * @param :currentUserId 当前登录用户id
     * @param :userId        被沟通人id
     */
    @GetMapping("/newQueryAdviceUserListByUserId/{userId}")
    @RequiresPermissions("biz:communicate:query")
    public AjaxResult newQueryAdviceUserListByUserId(@PathVariable Long userId) {
        Assert.notNull(userId, "被指派人用户id不能为空");
        List<SysTeam> list = new ArrayList<>();
        //指派人Id
        Long currentUserId = SecurityUtils.getUserId();
        SysTeam currTeam = null;
        R<SysTeam> result = teamService.getInfoById(userId, SecurityConstants.INNER);
        if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
            currTeam = result.getData();
        }
        if (null == currTeam) {
            return AjaxResult.success(list);
        }
        //如果是超级管理员，递归查询所有上级
        if (VerifyUtil.whetherAllPermissions()) {
            selectTeamByParentTeamId(currTeam, list);
            return AjaxResult.success(list);
        }
        //当前登陆人的team，
        SysTeam sysTeam = null;
        R<SysTeam> resultCur = teamService.getInfoById(currentUserId, SecurityConstants.INNER);
        if (StringUtils.isNotNull(resultCur) && StringUtils.isNotNull(resultCur.getData())) {
            sysTeam = resultCur.getData();
        }
        if (!ObjectUtils.isEmpty(currTeam.getParentId())) {
            SysTeam parentTeam = null;
            R<SysTeam> resultParentTeam = teamService.queryInfoByTeamId(currTeam.getParentId(), SecurityConstants.INNER);
            if (StringUtils.isNotNull(resultParentTeam) && StringUtils.isNotNull(resultParentTeam.getData())) {
                parentTeam = resultParentTeam.getData();
            }
            if (!parentTeam.getUserId().equals(currentUserId) && sysTeam.getLevel() <= parentTeam.getLevel()) {
                list.add(parentTeam);
            }
        }
        if (!ObjectUtils.isEmpty(currTeam.getSuperId())) {
            SysTeam superTeam = null;
            R<SysTeam> resultSuperTeam = teamService.queryInfoByTeamId(currTeam.getSuperId(), SecurityConstants.INNER);
            if (StringUtils.isNotNull(resultSuperTeam) && StringUtils.isNotNull(resultSuperTeam.getData())) {
                superTeam = resultSuperTeam.getData();
            }
            if (!superTeam.getUserId().equals(currentUserId)) {
                //不能指派给当前登录人的上级
                if (!ObjectUtils.isEmpty(sysTeam.getParentId()) && !sysTeam.getParentId().equals(superTeam.getTeamId()) && sysTeam.getLevel() <= superTeam.getLevel()) {
                    list.add(superTeam);
                }
            }
        }
        return AjaxResult.success(list);
    }


    public void selectTeamByParentTeamId(SysTeam currTeam, List<SysTeam> list) {
        SysTeam superTeam = null;
        R<SysTeam> resultParentTeam = teamService.queryInfoByTeamId(currTeam.getParentId(), SecurityConstants.INNER);
        if (StringUtils.isNotNull(resultParentTeam) && StringUtils.isNotNull(resultParentTeam.getData())) {
            superTeam = resultParentTeam.getData();
        }
        if (null != superTeam) {
            list.add(superTeam);
            selectTeamByParentTeamId(superTeam, list);
        } else {
            return;
        }
    }

    /**
     * 根据用户id获取所有沟通记录
     */
    @Log(title = "获取所有沟通记录", businessType = BusinessType.SELECT)
    @RequiresPermissions("@ss.hasAnyPermi('biz:communicate:query')")
    @GetMapping(value = "queryCommunicateByUserId/{userId}")
    public AjaxResult queryCommunicateByUserId(@PathVariable("userId") Long userId) {
        Assert.notNull(userId, "userId不能为空");
        List<CommunicateBean> list = communicateService.queryCommunicateByUserId(userId);
        return success(list);
    }
}
